package com.j4cf.auth.controller.user;

import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.j4cf.auth.dao.entity.AuthPermission;
import com.j4cf.auth.dao.entity.AuthRole;
import com.j4cf.auth.dao.entity.AuthUser;
import com.j4cf.auth.service.AuthApiService;
import com.j4cf.auth.service.AuthUserService;
import com.j4cf.common.base.BaseController;
import com.j4cf.common.base.BaseResult;
import com.j4cf.common.base.BaseResultEnum;
import com.j4cf.common.util.MD5Util;
import com.j4cf.common.validator.LengthValidator;
import com.j4cf.common.validator.NotNullValidator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: LongRou
 * @CreateDate: 2018 2018/4/26 16:53
 * @Version: 1.0
 **/
@RestController
@RequestMapping("/user/admin")
@Api(tags = {"Admin管理"}, description = "Admin管理")
public class AuthAdminController extends BaseController{
    private static final Logger LOGGER = LoggerFactory.getLogger(AuthAdminController.class);

    @Autowired
    private AuthUserService authUserService;
    @Autowired
    private AuthApiService authApiService;

    @ApiOperation(value = "获取用户信息",notes = "获取用户信息")
    @ApiImplicitParams({
    })
    @RequestMapping(value = "getUserInfo", method = RequestMethod.GET)
    public BaseResult getUserInfo(){
        // 当前登录用户权限
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        LOGGER.info(username+" 获取用户信息...");
        AuthUser authUser = authApiService.selectAuthUserByUsername(username);
        return new BaseResult(BaseResultEnum.SUCCESS, authUser);
    }

    @ApiOperation(value = "获取用户权限",notes = "获取权限，建立菜单使用")
    @ApiImplicitParams({
    })
    @RequestMapping(value = "getPermission", method = RequestMethod.GET)
    public BaseResult getPermission(){
        // 当前登录用户权限
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        LOGGER.info(username+" 获取权限列表...");
        AuthUser authUser = authApiService.selectAuthUserByUsername(username);
        List<AuthPermission> list = authApiService.selectAuthPermissionByAuthUserId(authUser.getUserId());
        return new BaseResult(BaseResultEnum.SUCCESS, list);
    }

    @ApiOperation(value = "获取用户角色",notes = "获取角色，建立菜单使用")
    @ApiImplicitParams({
    })
    @RequestMapping(value = "getRole", method = RequestMethod.GET)
    public BaseResult getRole(){
        // 当前登录用户权限
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        LOGGER.info(username+" 获取角色列表...");
        AuthUser authUser = authApiService.selectAuthUserByUsername(username);
        List<AuthRole> list = authApiService.selectAuthRoleByAuthUserId(authUser.getUserId());
        return new BaseResult(BaseResultEnum.SUCCESS, list);
    }

    @ApiOperation(value = "用户修改个人信息", notes = "用户修改个人信息")
    @RequestMapping(value = "/updateUserInfo" ,method = RequestMethod.PUT ,consumes = MediaType.APPLICATION_JSON_VALUE)
    public BaseResult updateUserInfo(@RequestBody AuthUser entity) {
        //信息校验
        ComplexResult result = FluentValidator.checkAll()
                .on(entity.getPhone(), new LengthValidator(11, 11, "手机号"))
                .on(entity.getRealname(), new NotNullValidator("真实姓名"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new BaseResult(BaseResultEnum.ERROR, result.getErrors().get(0).getErrorMsg());
        }
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        AuthUser authUser = authApiService.selectAuthUserByUsername(username);
        authUser.setPhone(entity.getPhone());
        authUser.setRealname(entity.getRealname());
        if (authUserService.updateById(authUser)){
            return new BaseResult(BaseResultEnum.SUCCESS,"修改成功！");
        }
        return new BaseResult(BaseResultEnum.ERROR,"修改失败！");
    }
    @ApiOperation(value = "用户修改个人密码", notes = "用户修改个人密码")
    @RequestMapping(value = "/updatePass" ,method = RequestMethod.PUT ,consumes = MediaType.APPLICATION_JSON_VALUE)
    public BaseResult updatePass(@RequestBody Map<String, Object> params) {
        //信息校验
        ComplexResult result = FluentValidator.checkAll()
                .on((String)params.get("oldPass"), new LengthValidator(5, 32, "老密码"))
                .on((String)params.get("newPass"), new LengthValidator(5, 32, "新密码"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new BaseResult(BaseResultEnum.ERROR, result.getErrors().get(0).getErrorMsg());
        }
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        AuthUser authUser = authApiService.selectAuthUserByUsername(username);
        String oldPass = (String)params.get("oldPass");
        String newPass = (String)params.get("newPass");
        if (!MD5Util.md5(oldPass + authUser.getSalt()).equals(authUser.getPassword())){
            return new BaseResult(BaseResultEnum.ERROR,"密码错误！");
        }

        authUser.setPassword(MD5Util.md5(newPass + authUser.getSalt()));
        if (authUserService.updateById(authUser)){
            return new BaseResult(BaseResultEnum.SUCCESS,"修改成功！");
        }
        return new BaseResult(BaseResultEnum.ERROR,"修改失败！");
    }

}
